package clientGUI;

import CommonObject.InfoChuyenTau;
import CommonObject.InfoDangKyVe;
import banvetauclient.BanVeTauClient;
import banvetauclient.Serializer;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class BookTicket extends JFrame {

	//public static Users user = null;
    private final JPanel contentPane;
    private final JTextField txtNumTicket;
    private final JTable tblRoute;
    private final JTextField txtCodeConfirm;
    private final JTextField txtReInputCodeConfirm;
    private JComboBox<InfoChuyenTau> combRoute;
    private final JLabel lblTuyenDuong;
    private final JLabel lblLoaiGhe;
    private InfoChuyenTau selectedTrain = null;
    private List<InfoDangKyVe> orderList = null;

    /**
     * Create the frame.
     */
    @SuppressWarnings("rawtypes")
    public BookTicket() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent arg0) {
                fillDataIntoCombobox();
            }
        });

        setTitle("Đặt vé");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 806, 572);
		//orderList = new ArrayList<Orders>();

        final JFrame parentForm = this;
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(54, 15, 15, 15));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblChuyn = new JLabel("Chuy\u1EBFn: ");
        lblChuyn.setBounds(277, 14, 79, 14);
        contentPane.add(lblChuyn);

        JLabel lblSLngV = new JLabel("S\u1ED1 l\u01B0\u1EE3ng v\u00E9 :");
        lblSLngV.setBounds(277, 132, 91, 14);
        contentPane.add(lblSLngV);

        txtNumTicket = new JTextField();
        txtNumTicket.setColumns(10);
        txtNumTicket.setBounds(378, 123, 150, 32);
        contentPane.add(txtNumTicket);

        JButton btnXoaVeDat = new JButton("Xóa vé đặt");
        btnXoaVeDat.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                RemoveBookTicket();
            }
        });
        btnXoaVeDat.setBounds(277, 164, 91, 23);
        contentPane.add(btnXoaVeDat);

        JButton btnBookTicket = new JButton("Đặt vé");
        btnBookTicket.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                InsertBookTicket();
            }
        });
        btnBookTicket.setBounds(437, 164, 91, 23);
        contentPane.add(btnBookTicket);

        combRoute = new JComboBox<InfoChuyenTau>();
        combRoute.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent arg0) {
                /*try
                 {
                 if(arg0.getStateChange() == ItemEvent.SELECTED)
                 {
                 selectedTrain  = ((Trains)combRoute.getSelectedItem());
                 if(selectedTrain!= null)
                 {
                 Stations startStation = selectedTrain.getStationsByStartStation();
                 Stations toStation = selectedTrain.getStationsByToStation();
                 if(startStation != null && toStation != null)
                 {
                 lblTuyenDuong.setText(startStation.getName() + " - " + toStation.getName());
                 }
							
                 Seats seat = selectedTrain.getSeats();
                 if(seat != null)
                 {
                 lblLoaiGhe.setText(seat.getName());
                 }
                 }
                 }
                 }
                 catch(Exception e)
                 {
                 selectedTrain = null;
                 lblTuyenDuong.setText("Chưa có");
                 lblLoaiGhe.setText("Chưa có");
                 e.printStackTrace(); 
                 }*/
            }
        });
        combRoute.setModel(new DefaultComboBoxModel(new String[]{"Chọn Tuyến..."}));
        combRoute.setBounds(378, 11, 150, 22);
        contentPane.add(combRoute);

        JLabel lblNewLabel = new JLabel("Danh sách đặt vé");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setBounds(331, 198, 159, 34);
        contentPane.add(lblNewLabel);

        txtCodeConfirm = new JTextField();
        txtCodeConfirm.setColumns(10);
        txtCodeConfirm.setBounds(305, 395, 150, 20);
        contentPane.add(txtCodeConfirm);

        txtReInputCodeConfirm = new JTextField();
        txtReInputCodeConfirm.setColumns(10);
        txtReInputCodeConfirm.setBounds(378, 437, 150, 20);
        contentPane.add(txtReInputCodeConfirm);

        JLabel lblNhpLi = new JLabel("Nhập lại ô chữ trên:");
        lblNhpLi.setBounds(260, 440, 108, 14);
        contentPane.add(lblNhpLi);

        JButton btnConfirm = new JButton("Xác nhận vé đặt");
        btnConfirm.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                SaveOrderList();
            }
        });
        btnConfirm.setBounds(260, 486, 129, 23);
        contentPane.add(btnConfirm);

        JButton btnExit = new JButton("Hủy bỏ");
        btnExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                parentForm.dispose();
            }
        });
        btnExit.setBounds(437, 486, 91, 23);
        contentPane.add(btnExit);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(0, 235, 790, 127);

        tblRoute = new JTable();
        tblRoute.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tblRoute.setCellSelectionEnabled(true);
        tblRoute.setColumnSelectionAllowed(true);
        tblRoute.setBorder(new LineBorder(new Color(0, 0, 0)));
        tblRoute.setModel(new DefaultTableModel(
                new Object[][]{},
                new String[]{
                    "STT", "Chuy\u1EBFn", "Ga \u0111\u1EBFn", "Ga \u0111i", "Th\u1EDDi gian", "S\u1ED1 l\u01B0\u1EE3ng", "\u0110\u01A1n gi\u00E1", "Th\u00E0nh ti\u1EC1n"
                }
        ));

        scrollPane.setViewportView(tblRoute);
        contentPane.add(scrollPane);

        JLabel lblTuynng = new JLabel("Tuyến đường:");
        lblTuynng.setBounds(277, 55, 79, 23);
        contentPane.add(lblTuynng);

        JLabel lblLoiGh = new JLabel("Loại ghế: ");
        lblLoiGh.setBounds(277, 89, 79, 23);
        contentPane.add(lblLoiGh);

        lblTuyenDuong = new JLabel("Chưa có");
        lblTuyenDuong.setBounds(378, 52, 150, 29);
        contentPane.add(lblTuyenDuong);

        lblLoaiGhe = new JLabel("Chưa có");
        lblLoaiGhe.setBounds(378, 89, 150, 29);
        contentPane.add(lblLoaiGhe);
    }

    //Fill data into the route combobox
    private void fillDataIntoCombobox() {
        /*//Open connection
         Session session = TicketUtil.getSessionFactory().openSession();
         List<Trains> lst = null;
         try
         {
         //Get Trains Data
         String queryCommand = "SELECT tr "  +
         "FROM Trains tr " + 
         "join fetch tr.stationsByStartStation ss "+ 
         "join fetch tr.stationsByToStation ts "+ 
         "join fetch tr.seats ss ";

         Query query = session.createQuery(queryCommand);
			
         lst = query.list();
			
         //fill data into combobox
         for(int i = 0; i < lst.size(); i++)
         {
         combRoute.addItem(lst.get(i));
         }
			
         }
         catch (HibernateException e) {
	         
         e.printStackTrace(); 
         }
         finally {
         //Close connection
         session.close(); 
         }*/

        try {
            byte[] infoBytes = new byte[BanVeTauClient.cis.read()];
            BanVeTauClient.cis.read(infoBytes);
            InfoChuyenTau[] s = (InfoChuyenTau[]) Serializer.deserialize(infoBytes);
            //fill data into combobox
            for (int i = 0; i < s.length; i++) {
                combRoute.addItem(s[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Insert the current book 
    private void InsertBookTicket() {
        try {
            //Check if user input the number of ticket
            if (txtNumTicket.getText() != null && !txtNumTicket.getText().isEmpty()) {
                int numTicket = Integer.parseInt(txtNumTicket.getText());
                //Create new order
                InfoDangKyVe newOrder = new InfoDangKyVe();

				//Set information for the order
				/*newOrder.setCode(new Date().toString() + user.getUsername());
                 newOrder.setStatus("PENDING");
                 newOrder.setPaid(0);
                 newOrder.setUsers(user);
                 newOrder.setAmount(numTicket);
                 newOrder.setTotal((double)(numTicket * selectedTrain.getPrice()));
                 newOrder.setTrains(selectedTrain);*/
                newOrder.TrainId = selectedTrain.IdChuyenDi;
                newOrder.Ammount = numTicket;
                newOrder.Total = (double) (numTicket * selectedTrain.Price);
                //add the new order to list
                orderList.add(newOrder);

                //add the information of new order to table
                int numRow = tblRoute.getRowCount() + 1;
                DefaultTableModel model = (DefaultTableModel) tblRoute.getModel();
                model.addRow(new Object[]{
                    numRow,
                    selectedTrain.TenChuyen,
                    selectedTrain.TenGaDen,
                    selectedTrain.TenGaDi,
                    null,
                    newOrder.Ammount,
                    selectedTrain.Price,
                    newOrder.Total
                });
            } else {
                JOptionPane.showMessageDialog(null, "You have not inputed the number of ticket yet", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error : " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }

    }

    //Remove the selected book 
    private void RemoveBookTicket() {
        int index = tblRoute.getSelectedRow();
        if (index >= 0) {
            DefaultTableModel model = (DefaultTableModel) tblRoute.getModel();
            model.removeRow(index);
            orderList.remove(index);
            JOptionPane.showMessageDialog(null, orderList.size(), "Error", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "You have not selected the order yet", "Error", JOptionPane.WARNING_MESSAGE);
        }
    }

    //Save the order list
    private void SaveOrderList() {
        /*Session session = TicketUtil.getSessionFactory().openSession();
         try
         {
         //Start the transaction
         session.beginTransaction();
         for(int i=0; i < orderList.size();i++)
         {
         session.save(orderList.get(i));
         }
         //Commit the transaction
         session.getTransaction().commit();
         JOptionPane.showMessageDialog (null, "The ticket book is accepted successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
			
         }
         catch (HibernateException e) {
         session.getTransaction().rollback();
         e.printStackTrace(); 
         }
         finally {
         session.close(); 
         }*/

        try {

            InfoDangKyVe[] dk = (InfoDangKyVe[])orderList.toArray();
            byte[] serialObject = Serializer.serialize(dk);
            BanVeTauClient.cos.write(1);
            BanVeTauClient.cos.write(serialObject.length);
            BanVeTauClient.cos.write(serialObject);
            BanVeTauClient.cos.flush();
            boolean result = BanVeTauClient.cis.readBoolean();
            if(result)
            {
                JOptionPane.showMessageDialog(null, "The ticket book is accepted successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
            }
            else
            {
                JOptionPane.showMessageDialog(null, "The ticket book is accepted fail", "Notice", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
